package cn.mymall.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * fastjson帮助工具类
 */
public class FastJsonUtil {
    private static Logger logger = LoggerFactory.getLogger(FastJsonUtil.class);
    private static final SerializeConfig serializeConfig = new SerializeConfig();

    static {
        ParserConfig.getGlobalInstance().addAccept("cn.xuankua");
    }

    /**
     * object -> json字符串
     *
     * @param object
     * @return
     */
    public static String toJsonString(Object object) {
        return toJsonString(object, false);
    }

    /**
     * object -> json字符串
     *
     * @param object
     * @param seralizerClass 是否序列化类信息
     * @return
     */
    public static String toJsonString(Object object, boolean seralizerClass) {
        if (object == null) return null;

        if (object instanceof String && StringUtils.isNotBlank((String) object)) {
            return "";
        }

        if (seralizerClass) {
            return JSON.toJSONString(object, serializeConfig, new SerializerFeature[]{SerializerFeature.WriteClassName});
        }
        return JSON.toJSONString(object, serializeConfig, new SerializerFeature[0]);
    }

    public static <T> T parseObject(String json, Class<T> cla) {
        if (StringUtils.isBlank(json)) return null;
        try {
            return JSON.parseObject(json, cla);
        } catch (JSONException jsonException) {
            logger.error("JSON解析异常，参数：{},异常：", json, jsonException);
            return null;
        }
    }

    public static Object parseObject(String json) {
        if (StringUtils.isBlank(json)) return null;
        try {
            return JSON.parse(json);
        } catch (JSONException jsonException) {
            logger.error("JSON解析异常，参数：{},异常：{}", json, jsonException);
            return null;
        }
    }

    public static <T> T parseObject(String json, TypeReference<T> typeReference) {
        if (StringUtils.isBlank(json)) return null;
        try {
            return JSON.parseObject(json, typeReference);
        } catch (JSONException jsonException) {
            logger.error("JSON解析异常，参数：{},异常：{}", json, jsonException);
            return null;
        }
    }

    public static <T> List<T> parseArray(String json, Class<T> cls) {
        if (StringUtils.isBlank(json)) return null;
        try {
            return JSON.parseArray(json, cls);
        } catch (JSONException jsonException) {
            logger.error("JSON解析异常，参数：{},异常：{}", json, jsonException);
            return null;
        }
    }
}
